<template>
    <div id="add-edit-model">
        <el-dialog
            :title="$t('key_13')"
            v-model="isDataDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="769px" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="20" :sm="20" :md="20" :lg="20" :xl="20" class="mb20">
                        <el-form-item :label="$t('key_33')" prop="dataScopeType">
                            <el-select value-key="code" @change="dataScopeTypeChange" v-model="ruleForm.dataScopeTypeName" :placeholder="$t('key_34')">
                                <el-option
                                    v-for="item in dataScopeTypeData"
                                    :key="item.code"
                                    :label="item.value"
                                    :value="item"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <template v-if="(ruleForm.dataScopeType === 5)">
                        <el-col :xs="20" :sm="20" :md="20" :lg="20" :xl="20" class="mb20">
                            <el-form-item :label="$t('key_32')">
                                <el-tree 
                                    ref="treeData"
                                    :data="choseMenuList" 
                                    :highlight-current="true" 
                                    :default-expand-all="true" 
                                    :expand-on-click-node="false" 
                                    :check-strictly="true"
                                    :default-checked-keys="defaultChecked"
                                    node-key="id"
                                    :props="defaultProps" 
                                    show-checkbox
                                    @check-change="handleNodeClick">
                                </el-tree>
                            </el-form-item>
                        </el-col>
                    </template>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelDataClick">{{ $t('key_24') }}</el-button>
                <el-button type="primary" :disabled="repeatDis" @click="submitForm(ruleFormRef)">{{ $t('key_25') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch, Ref } from 'vue'
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus'
import { sysDictTypeDropDown , getOrgTree , sysRoleOwnData , sysRoleGrantData} from '/@/api/manage/manage'
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
const { proxy } = useCurrentInstance();
const $t = proxy.$t;
import { log } from 'console'
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    dataScopeType:Number,
    dataScopeTypeName: String,
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        isDataDialog:{
            type: Boolean,
            default: false,
        },
        dataInfo: {
            type: Object,
            default: {}
        }
    },
    setup(props,ctx){
        const ruleFormRef = ref()
        const dataScopeTypeData = ref()
        const choseMenuList = ref()
        let treeData: Ref = ref(null)
        const defaultChecked = ref()
        const defaultProps: object = {
            children: 'children',
            label: 'title',
        }
        let menuObj:any[] = []

        /*** dataScopeTypeChange 授权范围选择事件 */
        const dataScopeTypeChange = (val:any) => {
            if(parseInt(toRaw(val.code)) === 5){
                GetUerData()
            }
            state.ruleForm.dataScopeType = parseInt(toRaw(val.code))
            state.ruleForm.dataScopeTypeName = val.value
        }

        /*** GetAuthInfo 获取授权范围数据 */
        const GetAuthInfo = async () => {
            try {
                let res: { data: any[] } = await sysDictTypeDropDown({ code: 'data_scope_type' })
                console.log(res.data)
                res.data.map(i => {
                    if(String(toRaw(props.dataInfo).dataScopeType) === i.code){
                        state.ruleForm.dataScopeTypeName = i.value
                        state.ruleForm.dataScopeType = Number(i.code)
                    }
                })
                dataScopeTypeData.value = res.data
            } catch (err) {} 
        }

        const GetTreeData = async () => {
            try {
                let res: { data: any[] } = await getOrgTree({ code: 'data_scope_type' })
                console.log(res.data,'树形数据')
                choseMenuList.value = res.data
            } catch (err) {} 
        }

        /*** GetUerData 获取用户已经有的数据 */
        const GetUerData = async () => {
            try {
                let res: { data: any[] } = await sysRoleOwnData({ id: props.dataInfo.id })
                defaultChecked.value = res.data
            } catch (err) {}
        }

        /*** handleNodeClick 树型当前节点点击事件 */
        const handleNodeClick = () => {
            let res1 = treeData.value.getCheckedKeys()
            menuObj = [...res1]
        }

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            dataScopeType: [
				{ required: true, message: $t('key_35'), trigger: 'blur' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelDataClick')
        }

        /*** cancelDataClick 取消事件 */
        const cancelDataClick = () => {
            ctx.emit('cancelDataClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => {
                if(valid){
                    let setArr:any[] = []
                    if(state.ruleForm.dataScopeType !== 5){
                        setArr = []
                    }else{
                        if(menuObj.length !== 0){
                            menuObj.map(i => {
                                setArr.push(String(i))
                            })
                        }
                    }
                    let param = {
                        id: String(toRaw(props.dataInfo).id),
                        grantOrgIdList: setArr,
                        dataScopeType: state.ruleForm.dataScopeType
                    }
                    console.log(param,'param')
                    try {
                        let res:any = await sysRoleGrantData(param)
                        if(res.success){
                            state.repeatDis = true
                            ctx.emit('controlDataClick')
                            ctx.emit('updateData')
                        }else{
                            state.repeatDis = true
                            ctx.emit('controlDataClick')
                        }
                    } catch (err) { return }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** 监听isDataDialog的变化 */
        watch(() => props.isDataDialog,(newVal) => {
            if(newVal){
                state.repeatDis = false
                if(props.dataInfo.dataScopeType === 5){
                    GetUerData()
                }
                GetAuthInfo()
                GetTreeData()
            }
        })

        /*** isDataDialog 响应弹窗的关闭  */
        const isDataDialog = computed(() => {
            return props.isDataDialog
        })

        return {
            handleClose,
            submitForm,
            cancelDataClick,
            clean,
            ruleFormRef,
            ...toRefs(state),
            isDataDialog,
            rules,
            dataScopeTypeChange,
            dataScopeTypeData,
            defaultProps,
            treeData,
            choseMenuList,
            defaultChecked,
            handleNodeClick
        }
    },
} )
</script>
<style scoped lang="scss">
    .mb20{
        margin: auto;
    }
    :deep(.el-select){
        width: 100%;
    }  
    :deep(.el-tree){
        width: 100%;
    }
</style>